package main

import (
	"fmt"
	"database/sql"
	"time"
)

func openDbString(sqlstring string) string {
	conn := DB
	defer conn.Close()
	stmt, err := conn.Prepare(sqlstring)
	if err != nil {
		fmt.Println("Query Error", err)
		return "Error"
	}
	defer stmt.Close()
	rows, err := stmt.Query()
	if err != nil {
		fmt.Println("Query Error", err)
		return "Error"
	}
	defer rows.Close()
	// Get column names
	columns, err := rows.Columns()
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	// Make a slice for the values
	values := make([]sql.RawBytes, len(columns))
	// rows.Scan wants '[]interface{}' as an argument, so we must copy the
	// references into such a slice
	// See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details
	scanArgs := make([]interface{}, len(values))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	// Fetch rows
	var jsonstring string
	jsonstring = "{\"timestamp\": \"" + time.Now().Format("2006-01-02 15:04:05") + "\",\"data\":["
	allcount := 0

	for rows.Next() {
		jsonstring += "{"
		// get RawBytes from data
		err = rows.Scan(scanArgs...)
		if err != nil {
			panic(err.Error()) // proper error handling instead of panic in your app
		}
		// Now do something with the data.
		// Here we just print each column as a string.
		var value string
		for i, col := range values {
			// Here we can check if the value is nil (NULL value)
			if col == nil {
				value = "NULL"
			} else {
				value = string(col)
			}
			//          fmt.Println(columns[i], ": ", value)
			if i == len(values)-1 {
				jsonstring += "\"" + columns[i] + "\":\"" + value + "\""
			} else {
				jsonstring += "\"" + columns[i] + "\":\"" + value + "\","
			}
			//          fmt.Println(" :", i, ": ", col, len(values))
		}
		//fmt.Println("replace before :", jsonstring, ": ", len(jsonstring))
		//jsonstring = strings.Replace(jsonstring, ",", " ", len(jsonstring))
		//fmt.Println("replace after :", jsonstring, ": ", len(jsonstring))
		//      fmt.Println("-----------------------------------", allcount)

		jsonstring += "},"
		allcount++
	}
	if allcount > 0 {
		//jsonstring = Substr(jsonstring, 0, len(jsonstring)-1)
		jsonstring = jsonstring[0:len(jsonstring)-1]
	}
	jsonstring += "]}"

	if err = rows.Err(); err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	return jsonstring
}
